<?php

namespace Console\Logic;

use \Common\Logic\BaseLogic;

/**
 * 鉴权控制器
 */
class AuthLogic extends BaseLogic {

    const USER_COOKIE_NAME = 'console_user_info';
    const USER_FIELD = 'id,phone,name';
    const CRYPT_KEY = 'FmL2UrsftJeF7LecaBh0V7UZHiQ7VsDN';

    private $userModel;

    public function __construct() {
        parent::__construct();
        $this->userModel = D('User');
    }

    /**
     * 从cookie获取登陆信息
     * @return type
     */
    public function getUserInfo() {
        $userInfoRes = $this->getUserInfoByCookie();
        if (static::$res->isErr($userInfoRes)) {
            return static::$res->err("用户未登陆");
        }
        $userCookieInfo = $userInfoRes['Result'];
        if ($userCookieInfo['expire'] < time()) {
            return static::$res->err("登陆信息已过期");
        }

        //重新获取登陆数据，防止后台修改
        $userWhere = array(
            "id" => $userCookieInfo['id'],
            "state" => 1
        );
        $userInfo = $this->userModel->where($userWhere)->field(static::USER_FIELD)->find();
        if (empty($userInfo)) {
            return static::$res->err("登陆账户不存在");
        }

        //让登陆过去时间+1day
        $userInfo['expire'] = $userCookieInfo['expire'] + 3600 * 24;

        //重新写入cookie
        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 登录账号
     * @param type $phone
     * @param type $pwd
     * @param type $expire
     * @return type
     */
    public function login($phone, $pwd, $expire = "") {
        if (empty($phone)) {
            return static::$res->err("登陆账户不能为空");
        }
        if (empty($pwd)) {
            return static::$res->err("密码不能为空");
        }

        $pwd = $this->md5Password($pwd);
        $where = array(
            "phone" => $phone,
            "pwd" => $pwd,
            "state" => 1
        );

        $userInfo = $this->userModel->where($where)->field(static::USER_FIELD)->find();
        if (empty($userInfo)) {
            return static::$res->err("账号或密码错误");
        }

        if (empty($expire)) {
            $expire = strtotime("+1 day");
        }

        $userInfo['expire'] = strtotime("+1 day");
        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 退出登录
     */
    public function logout() {
        cookie(static::USER_COOKIE_NAME, null);
    }

    /**
     * 通过cookie获取登录信息
     * @return mixed
     */
    private function getUserInfoByCookie() {
        $cookieStr = cookie(static::USER_COOKIE_NAME);
        if (empty($cookieStr)) {
            return static::$res->err("登录信息不存在");
        }
        $userInfoJson = \Think\Crypt::decrypt($cookieStr, static::CRYPT_KEY);
        $userInfo = json_decode($userInfoJson, true);
        if (empty($userInfo)) {
            return static::$res->err("登录信息失效");
        }
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 将用户信息写入到cookie
     * @param type $userInfo
     */
    private function setUserInfoToCookie($userInfo) {
        $userInfoJson = json_encode($userInfo);
        $val = \Think\Crypt::encrypt($userInfoJson, static::CRYPT_KEY);
        cookie(static::USER_COOKIE_NAME, $val, 365 * 24 * 3600);
    }

    /**
     * 加密密码
     * @param $password
     * @return string
     */
    private function md5Password($password) {
        $val = md5($password);
        return $val;
    }

    /**
     * 查找一条用户数据
     * @param array $where
     * @return type
     */
    public function find($where) {
        $where["state"] = 1;
        $data = $this->userModel->where($where)->find();
        return $data;
    }

    /**
     * 获取用户列表
     * @param array $where
     * @return type
     */
    public function getUserList($where = array()) {
        $where["state"] = 1;
        $data = $this->userModel->where($where)->order("id desc")->select();
        return $data;
    }

    /**
     * 添加用户
     * @param type $userId
     * @param type $data
     * @return type
     */
    public function addUser($userId, $data = array()) {
        if (empty($userId)) {
            return static::$res->err("编辑人不能为空");
        }
        $fields = array(
            "phone" => array("empty" => "登陆账号不能为空", "mobile" => "请输入正确的手机格式"),
            "pwd" => array("empty" => "密码不能为空"),
            "repwd" => array(),
            "name" => array()
        );

        $verifyRes = $this->verifyData($fields, $data);
        if (static::$res->isErr($verifyRes)) {
            return $verifyRes;
        }
        $data = $verifyRes['Result'];

        $checkWherer = array(
            "phone" => $data["phone"],
            "state" => 1
        );
        if ($this->userModel->where($checkWherer)->count()) {
            return static::$res->err("手机号已存在");
        }

        if ($data["pwd"] != $data["repwd"]) {
            return static::$res->err("两次密码不一致");
        }
        unset($data["repwd"]);
        $data["pwd"] = $this->md5Password($data["pwd"]);
        $data['add_time'] = date("Y-m-d H:i:s");
        $data['add_user'] = $userId;

        $id = $this->userModel->add($data);
        if (empty($id)) {
            return static::$res->err("数据库异常");
        }

        return static::$res->suc("成功", $id);
    }

    /**
     * 编辑用户
     * @param type $id
     * @param type $data
     * @return type
     */
    public function editUser($userId, $id, $data = array()) {
        if (empty($userId)) {
            return static::$res->err("编辑人不能为空");
        }
        if (empty($id)) {
            return static::$res->err("编辑ID不能为空");
        }

        $infoWherer = array(
            "id" => $id,
            "state" => 1
        );
        if (!$this->userModel->where($infoWherer)->count()) {
            return static::$res->err("用户数据不存在");
        }

        $fields = array(
            "phone" => array("empty" => "登陆账号不能为空", "mobile" => "请输入正确的手机格式"),
            "pwd" => array(),
            "repwd" => array(),
            "name" => array()
        );

        $verifyRes = $this->verifyData($fields, $data);
        if (static::$res->isErr($verifyRes)) {
            return $verifyRes;
        }
        $data = $verifyRes['Result'];

        foreach ($data as $key => $val) {
            if (empty($val)) {
                unset($data[$key]);
            }
        }

        $checkWherer = array(
            "phone" => $data["phone"],
            "id" => array("neq", $id),
            "state" => 1
        );
        if ($this->userModel->where($checkWherer)->count()) {
            return static::$res->err("手机号已存在");
        }

        if (!empty($data["pwd"])) {
            if ($data["pwd"] != $data["repwd"]) {
                return static::$res->err("两次密码不一致");
            }

            unset($data["repwd"]);
            $data["pwd"] = $this->md5Password($data["pwd"]);
        }

        $data['edit_time'] = date("Y-m-d H:i:s");
        $data['edit_user'] = $userId;

        $count = $this->userModel->where("id=$id")->save($data);
        if (empty($count)) {
            return static::$res->err("数据库异常");
        }

        return static::$res->suc("成功");
    }

    /**
     * 删除用户
     * @param type $userId
     * @param type $id
     * @return type
     */
    public function delUser($userId, $id) {
        if (empty($userId)) {
            return static::$res->err("编辑人不能为空");
        }
        if (empty($id)) {
            return static::$res->err("编辑ID不能为空");
        }

        $data = array(
            "state" => -1
        );
        $data['edit_time'] = date("Y-m-d H:i:s");
        $data['edit_user'] = $userId;

        $count = $this->userModel->where("id=$id")->save($data);
        if (empty($count)) {
            return static::$res->err("数据库异常");
        }

        return static::$res->suc("成功");
    }

}
